<template>
  <div class="login">
    <div class="error">{{ message }}</div>
    <form>
      <div class="lable">
        <input
          name="username"
          type="text"
          v-model.trim="username"
          placeholder="请输入用户名"
        />
        <input
          type="password"
          v-model.trim="password"
          placeholder="请输入密码"
        />
      </div>
      <div class="submit">
        <input type="submit" @click.prevent="login" value="登录" />
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { loginApi } from '@/api/api'
import { useUserStore } from '@/stores'
import { RouteLocationRaw, useRoute, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
const store = useUserStore()
console.log(store)
const username = ref('')
const password = ref('')
const message = ref('')
const login = async () => {
  message.value = ''
  if (!checkForm()) return
  const { data } = await loginApi({
    username: username.value,
    password: password.value,
  })
  if (data) {
    console.log(data)
    store.saveUser({
      username: data.username,
      id: data.id,
    })
    username.value = ''
    password.value = ''
    // 如果存在查询参数
    if (route.query.redirect) {
      const redirect = route.query.redirect
      router.replace(redirect as RouteLocationRaw)
    } else {
      router.replace('/')
    }
  }
}

const checkForm = () => {
  if (!username.value || !password.value) {
    ElMessage({ message: '用户名和密码不能为空', type: 'error' })
    return false
  }
  return true
}
</script>

<style scoped>
.login {
  margin: 5em auto 0;
  width: 44%;
}

.login input {
  padding: 15px;
  width: 94%;
  font-size: 1.1em;
  margin: 18px 0px;
  color: gray;
  float: left;
  cursor: pointer;
  font-family: 'HelveticaNeue', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  outline: none;
  font-weight: 600;
  margin-left: 3px;
  background: #eee;
  transition: all 0.3s ease-out;
  border: solid 1px #ccc;
}

.login input:hover {
  color: rgb(180, 86, 9);
  border-left: solid 6px #40a46f;
}

.login {
  padding: 5px 4px;
  text-align: center;
}
input[type='submit'] {
  padding: 17px 17px;
  color: #fff;
  float: right;
  font-family: 'HelveticaNeue', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background: #40a46f;
  border: solid 1px #40a46f;
  cursor: pointer;
  font-size: 18px;
  transition: all 0.5s ease-out;
  outline: none;
  width: 100%;
}

.submit input[type='submit']:hover {
  background: #07793d;
  border: solid 1px #07793d;
}

.login .error {
  color: red;
  font-weight: bold;
  font-size: 1.1em;
}
</style>
